<template>
  <div class="content">
    <nut-navbar class="navbar" z-index="5" :clickable="false" fixed safe-area-inset-top>
      <template #content>
        <span>{{ t(String(route.meta.title)) }}</span>
      </template>
      <template #left>
        <img src="/imgs/club/arrow_left.png" alt="" @click="router.go(-1)" class="arrow_left" />
      </template>
      <template #right>
        <!-- <span @click="onSubmitCreate" class="save">保存</span> -->
      </template>
    </nut-navbar>
    
    <div class="form_box">
      <nut-form label-position="top" ref="formRef" :model-value="createParams" :rules="rules" >
        <nut-form-item label="" >
          <div class="top_upload">
            <nut-uploader
                accept=".jpg,.jpeg,.png,.gif,.webp"
                :before-xhr-upload="beforeUpload"
                @delete="(e) => {removeImg(e)}"
            >
            </nut-uploader>
            <p>{{t('club_page_updata_img')}}</p>
            <p>{{ t('club_page_gs') }}</p>
          </div>
        </nut-form-item>
        <nut-form-item :label="t('club_page_jlbmc')" prop="club_name" :rules="rules.club_name">
          <nut-input 
            v-model.trim="createParams.club_name" 
            show-word-limit
            :max-length="40" 
            :placeholder="t('club_page_qsrmz')"
             @blur="blurValidate('club_name')"
            clearable 
          />
          <!-- <span class="tips">{{ t('club_page_40') }}</span> -->
        </nut-form-item>
        <nut-form-item :label="t('club_page_jlbjj')" prop="club_introduction" :rules="rules.club_introduction" class="dec">
          <nut-textarea 
            :rows="3" 
            limit-show
            :max-length="200" 
            v-model.trim="createParams.club_introduction" 
            :placeholder="t('club_page_qsrjj')" 
             @blur="blurValidate('club_introduction')"
            clearable 
          />
          <!-- <span class="tips1">{{ t('club_page_200') }}</span> -->
        </nut-form-item>
      </nut-form>
    </div>

    <div class="bottom_btn">
      <Btn height="44px" width="320px" class="submit" @click="submitAc">{{t('btn_label_submit')}}</Btn>
    </div>
  </div>
</template>

<script setup lang="ts">
import { showToast, showNotify } from "@nutui/nutui";
import { useI18n } from "vue-i18n";
import { ref, watch, onMounted, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import {storeToRefs} from "pinia";
import {User} from "@/store/user.ts";
import pinia from "@/store";
import Btn from "@/components/Btn.vue";
import { joinURL } from '@/utils/publicMethods'

import PKwebsocket from "@/lolo/Ws";
import { NetPacket } from "@/netBase/NetPacket";

import { Page } from "@/store/page.ts";
const PageStore = Page(pinia);
const { settings } = storeToRefs(PageStore);
const formRef = ref()
const route = useRoute();
const router = useRouter();
const UserStore = User(pinia);
const { roleInfo } = storeToRefs(UserStore);

const { t } = useI18n();

// 创建俱乐部表单提交
const createParams = ref({
  club_name: '',
  club_introduction: '',
  club_logo: '',
});

// 校验规则
const rules = ref({
  // club_logo: [{ required: true, message: t('club_page_updata_img') }],
  club_name: [
    { required: true, message: t('club_page_jlbmzbnwk') },
    { min: 2, max: 40, message: t('club_page_jlbmz40') },
  ],
  club_introduction: [
    { required: true, message: t('club_page_jlbjjbnwk') },
    { max: 200, message: t('club_page_jlbjj200') },
  ],
});

// 上传图片
const beforeUpload = (xhr: any, data: any) => {
  console.log('xhr',xhr);
  console.log('data',data);
  const file = data.sourceFile;

  if (file && file.size > 1024 * 1024 * 10) {
    // 2MB限制
    showNotify.danger(t('home_page_avatar_tip'));
    return;
  }
  const formData = new FormData();
  formData.append("image", file);
  formData.append("device_id", `${roleInfo.value.id}`);
  fetch(joinURL(settings.value.api_url, `/api/upload/img`), {
    method: "POST",
    body: formData,
  })
    .then((response) => response.json())
    .then((response) => {
      if (response.status == 200 || response.status == "success") {
        const urlImg = response.data.path;
        showNotify.success(t("operation_success"));
        createParams.value.club_logo = urlImg;
      } else {
        showNotify.danger(t('club_page_updata_err'));
      }
    });
};

const removeImg = (e: any) => {
  console.log('删除---', e)
}

// 单独校验某个字段
const blurValidate = (prop: string) => {
  formRef.value?.validate(prop).then()
};

// 提交表单方法
const submitAc = () => {
  if (!createParams.value.club_logo) {
    // return showToast.text(t('club_page_updata_img'))
    createParams.value.club_logo = 'club_logo'
  }
  formRef.value?.validate().then(({ valid, errors }: any) => {
    if (valid) {
      const req = NetPacket.req_create_club();
      req.club_name = createParams.value.club_name
      req.club_introduction = createParams.value.club_introduction
      req.club_logo = createParams.value.club_logo

      PKwebsocket.instance.send(req, true, {
        callbackName: "msg_notify_create_club",
        callback: createClubHandle,
      });
    } else {
      console.warn('error:', errors);
    }
  });
};

// 监听创建俱乐部返回
const createClubHandle = (res: any) => {
  const tipStr: any = {
    0: t('club_page_jlbcjcg'),
    1: t('club_page_csblbd'),
    2: t('club_page_jlbmzcz'),
    3: t('club_page_jlbdlbzq'),
    4: t('club_page_jlbslsx'),
    5: t('club_page_jlbmcjj'),
  };
  if (res.result === 0) {
    showToast.text(tipStr[res.result])
    router.push({
      path: "/club/detail",
      query: {
        club_id: res.club_id,
      },
    });
  } else {
    showToast.text(tipStr[res.result])
  }
};

watch(() => createParams.value.club_name, (newVal) => {
  if (newVal.length > 40) {
    createParams.value.club_name = newVal.slice(0, 40);
  }
});

watch(() => createParams.value.club_introduction, (newVal) => {
  if (newVal.length > 200) {
    createParams.value.club_introduction = newVal.slice(0, 200);
  }
});

onUnmounted(() => {
});

onMounted(() => {
  
});

</script>

<style scoped lang="scss">
.content {
  font-size: 14px;
  margin: 0 0 10px;
  color: #fff;

  .arrow_left {
    width: 24px;
    height: 24px;
  }

  .top_upload {
    padding: 15% 0 0;
    p {
      font-size: 15px;
      color: rgba(192, 194, 219, 1);
      text-align: center;
      margin-top: 10px;
    }
    :deep(.nut-uploader) {
      margin: 0 auto;
      width: 120px;
      height: 120px;
      background: rgba(26, 12, 66, 1);
      border: 1px solid rgba(50, 44, 89, 1);
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;

      .nut-uploader__upload {
        background: url(/imgs/club/add_ren.png) center no-repeat;
        background-size: 70px;
        border-radius: 50%;

        &::before {
          content: '';
          position: absolute;
          width: 32px;
          height: 32px;
          border-radius: 50%;
          bottom: 0;
          right: 6px;
          background: radial-gradient(100% 103.23% at 50% 0%, #1170FF 0%, #1154FF 61.51%, #6B11FF 98.5%);
        }
        svg {
          width: 24px;
          height: 24px;
          color: #fff !important;
          position: absolute;
          bottom: 4px;
          right: 10px;
        }
      }
      .nut-uploader__upload, .nut-uploader__preview, .nut-uploader__preview-img {
        width: 120px;
        height: 120px;
        border-radius: 50%;
        margin-right: 0;
        .close {
          color: #fff;
        }
      }
      .nut-uploader__preview__progress {
        display: none;
      }
      .nut-uploader__preview-img__c {
        width: 120px;
        height: 120px;
        border-radius: 50%;
      }
    }
  }

  .form_box {
    width: 347px;
    // height: 176px;
    margin: 10px auto 0;
    padding: 10px;
    border-radius: 8px;
    // background: #100E26;
    // box-shadow: 0.5px 0.5px 1px 0px #2E296B inset;
    form {
      .add_title {
        font-size: 14px;
        color: #fff;
        margin-bottom: 10px;
      }

      :deep(.nut-cell-group__wrap) {
        box-shadow: none;
        background: none;
        margin: 0;

        .nut-cell {
          background: none;
          padding: 0;
          margin-bottom: 14px;

          &::after {
            border: none;
          }

          &.nut-form-item {

            .nut-form-item__label {
              color: #fff;
            }
            .nut-input,
            .nut-textarea {
              color: #fff;
              width: 100%;
              background: #1D1C3C;
              box-shadow: 0.5px 0.5px 1px 0px #333260 inset;
              border: 1px solid #1D1C3C;
              border-radius: 8px;
              
              padding: 10px !important;
              .nut-textarea__textarea {
                color: #fff;
                height: 175px;
              }
              .nut-textarea__textarea::placeholder {
                color: #504F6F;  /* 修改为你想要的颜色 */
                opacity: 1;   /* 确保透明度是完全显示的 */
              }
              .nut-textarea__limit{
                color: #504F6F; 
              }
            }
          }
        }
      }

      :deep(.nut-form-item) {
        padding: 0 0 14px 0 !important;
        // position: relative;

        // .nut-cell__title {
        //   display: none !important;
        // }
        // .tips {
        //   position: absolute;
        //   right: 10px;
        //   top: 40px;
        //   color: #504F6F;
        //   font-family: "PingFang SC";
        //   font-size: 14px;
        //   font-style: normal;
        //   font-weight: 400;
        //   line-height: 14px; /* 100% */
        // }
        // .tips1 {
        //   position: absolute;
        //   right: 10px;
        //   top: 200px;
        //   color: #504F6F;
        //   font-family: "PingFang SC";
        //   font-size: 14px;
        //   font-style: normal;
        //   font-weight: 400;
        //   line-height: 14px; /* 100% */
        // }
      }

      :deep(.nut-cell-group__wrap) {
        box-shadow: none;
        margin: 0;
      }

      :deep(.nut-form-item__body__slots) {
        display: flex;
        justify-content: center;
      }

      :deep(.nut-cell-group .nut-cell::after) {
        border: none;
      }

      :deep(.nut-form-item.error.line::before) {
        border: none;
      }

      :deep(.nut-input-right-box) {
        position: relative;
      }
      // :deep(.nut-input-inner) {
      //   width: 228px;
      // }
      :deep(.input-text) {
        &::placeholder {
          color: #504F6F !important;
        }
      }

    }
  }

  .bottom_btn {
    display: flex;
    justify-content: center;
    align-items: center;
    // position: fixed;
    // bottom: 56px;
    // left: 50%;
    // transform: translateX(-50%);
    // z-index: 99;
  }
}
</style>
